package com.kitty.game.shidao;

import com.kitty.common.cache.RedisService;
import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.activity.model.user.ShiDaoTopRecord;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.config.NPC;
import com.kitty.game.config.Server;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.service.OneThreadService;
import com.kitty.game.fuling.model.Fuling;
import com.kitty.game.gm.GmCommandHandler200;
import com.kitty.game.hunqiao.model.HunQiaoData;
import com.kitty.game.mail.model.Mail;
import com.kitty.game.mail.service.MailService;
import com.kitty.game.npc.NpcDataPool;
import com.kitty.game.npc.message.RespNpcContent;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.KuafuService;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.common.utils.DecodeSendMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.http.Request;
import org.nutz.http.Sender;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.concurrent.ConcurrentHashMap;

import static com.kitty.game.npc.model.NpcButton.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class KuafuShidaoService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    TeamService teamService;
    @Autowired
    ServerService serverService;
    @Autowired
    KuafuService kuafuService;
    @Autowired
    RoleService roleService;
    @Autowired
    MailService mailService;
    @Autowired
    RedisService redisService;
    @Autowired
    Dao dao;
    //pos.setMapId(38000);
    //                    pos.setX((short) 20);
    //                    pos.setY((short) 20);
    //                    pos.setDir((byte) 8);
    public int mapId = 38000;
    public short x = 20;
    public short y = 20;
    public String content;

    ConcurrentHashMap<Integer, Integer> roleId_roleId = new ConcurrentHashMap<>();

    public String point() {
        String content = "我在此接引本区组玩家前往#R跨服区组#n参加#R各项跨服赛事#n，欢迎各位道友踊跃参加。" +
                "[" + kuafu_jingji_shengqin.getKey() + "]" +
//                "["+kuafu_jingji_enter.getKey()+"]" +
                "";
        String tail = "[我要查看跨服试道/menu_kuafu_shidao][我要查看名人争霸/menu_kuafu_mingren][离开]";
        return content + tail;
    }

    public void init() {
        NpcDataPool.npcButtonHandlers.put(NpcButton.kuafu_jingji_shengqin.getKey(), (npcButtonParam -> SpringUtils.getBean(KuafuShidaoService.class).prepare(npcButtonParam.getRole(), npcButtonParam.getMsg(), npcButtonParam.getNpc())));
        NpcDataPool.npcButtonHandlers.put(NpcButton.kuafu_jingji_enter_shidao.getKey(), (npcButtonParam -> SpringUtils.getBean(KuafuShidaoService.class).apply(npcButtonParam.getRole(), npcButtonParam.getMsg(), npcButtonParam.getNpc())));
        NpcDataPool.npcButtonHandlers.put(NpcButton.kuafu_jingji_enter_shidao_sure.getKey(), (npcButtonParam -> SpringUtils.getBean(KuafuShidaoService.class).enter(npcButtonParam.getRole(), npcButtonParam.getMsg(), npcButtonParam.getNpc())));
        NpcDataPool.npcButtonHandlers.put(kuafu_jingji_back.getKey(), (npcButtonParam -> SpringUtils.getBean(KuafuShidaoService.class).back(npcButtonParam.getRole(), npcButtonParam.getMsg(), npcButtonParam.getNpc())));
    }

    private void enter(Role role, String msg, NPC npc) {
        SpringUtils.getBean(ShiDaoHandler.class).doEnterShiDaoMap(role);
    }

    public void sendReward(String content){
        ShiDaoTopRecord shiDaoTopRecord = Json.fromJson(ShiDaoTopRecord.class,content);
        String name = shiDaoTopRecord.getName();
        if (!name.endsWith(serverService.getServer().getName())){
            return;
        }
        name = name.substring(0,name.lastIndexOf("_"));
        logger.error("原线路接收奖励=={}=={}",name,content);
//        name = name.split("_")[0];
        GmCommandHandler200 gmCommandHandler200 = SpringUtils.getBean(GmCommandHandler200.class);
        Role role = SpringUtils.getRoleService().getOnlinePlayer(name);
        if (role == null){
            long uid = gmCommandHandler200.getUidByName(name);
            role = SpringUtils.getRoleService().getPlayerBy(uid);
            if (role == null){
                return;
            }
        }
        send(role, (byte) shiDaoTopRecord.getRank());
        logger.error("跨服试道奖励=={}=={}=={}=={}",role.getRoleId(),role.getName(),Json.toJson(shiDaoTopRecord,JsonFormat.compact()));
    }

    public void send(Role role, byte rank) {
        ShiDaoHandler shiDaoHandler = SpringUtils.getBean(ShiDaoHandler.class);
        StringBuilder rewardDesc = new StringBuilder();

        Mail mail = SpringUtils.getMailService().createMail("跨服试道第"+rank+"名奖励", "跨服试道奖励", 7 * TimeUtil.ONE_DAY);
        ArrayList<NutMap> maps = new ArrayList<>();
        String reward = DataCache.REDIS_DATA.get("kuafu_shidao_reward_" + rank);
        if(StringUtils.isNotEmpty(reward)){
            for (String s : reward.split("\\+")) {
                NutMap nutMap = DecodeSendMessage.buildSendRewardMessage(s);
                maps.add(nutMap);
            }
            mail.getDatas().addAll(maps);
            SpringUtils.getMailService().sendNewMail(role, mail);
        }
        if (rank == 1){
            rewardDesc.append("#R"+Const.TITLE_NAME_SHIDAO_FIRST_kuafu+"#n");
            SpringUtils.getRoleService().addTitle(role, new TitleInfo(Const.TITLE_TYPE_SHIDAO, Const.TITLE_NAME_SHIDAO_FIRST_kuafu));
        }
        if (rank == 2){
            rewardDesc.append("#R"+Const.TITLE_NAME_SHIDAO_SECOND_kuafu+"#n");
            SpringUtils.getRoleService().addTitle(role, new TitleInfo(Const.TITLE_TYPE_SHIDAO, Const.TITLE_NAME_SHIDAO_SECOND_kuafu));
        }
        if (rank ==3){
            rewardDesc.append("#R"+Const.TITLE_NAME_SHIDAO_THIRD_kuafu+"#n");
            SpringUtils.getRoleService().addTitle(role, new TitleInfo(Const.TITLE_TYPE_SHIDAO, Const.TITLE_NAME_SHIDAO_THIRD_kuafu));
        }
        /**发系统消息*/
        String name = role.getName();
        String dateStr = TimeUtil.formatDate(new Date(), "yyyy年MM月dd日");
        String levelRange = shiDaoHandler.getLevelRange(shiDaoHandler.getRange(role.getLevel()));
        String rankChinese = Const.ORDER_CHINESE.get((int) rank);
        String content = MessageFormat.format(shiDaoHandler.REWARD_CONTENT, name, dateStr, levelRange, rankChinese, rewardDesc+"称号");
        SpringUtils.getChatService().sendSystem(content, Const.BRODCAST_MSG_TYPE_ROLE);
    }


    private void apply(Role role, String msg, NPC npc) {
        String content = SpringUtils.getBean(ShiDaoHandler.class).canEnter(role);
        if (content != null) {
            RespNpcContent respNpcContent = new RespNpcContent();
            respNpcContent.setNpcName(npc.getName());
            respNpcContent.setNpcId(npc.getId());
            respNpcContent.setContent(content);
            respNpcContent.setNpcIcon(npc.getIcon());
            MessagePusher.pushMessage(role, respNpcContent);
            return;
        }
        content = "我在此接引本区组玩家前往#R跨服区组#n参加#R各项跨服赛事#n，欢迎各位道友踊跃参加。[" + kuafu_jingji_enter_shidao_sure.getKey() + "][离开]";
        RespNpcContent respNpcContent = new RespNpcContent();
        respNpcContent.setNpcName(npc.getName());
        respNpcContent.setNpcId(npc.getId());
        respNpcContent.setContent(content);
        respNpcContent.setNpcIcon(npc.getIcon());
        MessagePusher.pushMessage(role, respNpcContent);
    }

    private void prepare(Role role, String msg, NPC npc) {
        //拷贝数据到跨服数据库
//        Team team = teamService.getTeam(role.getRoleId());
//        if (team == null){
//            MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有队伍。"));
//            return;
//        }
        if (serverService.getNeice() == 100){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("内测不能进入跨服试道"));
            return;
        }
        if (role.getLevel() < 75){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("低于75级不能参加跨服试道。"));
            return;
        }
        Server kuafu = serverService.getKuafuServer();
        if (content == null || content.equals("")){
            logger.error("跨服试道提示=={}",content);
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服试道还未开始。"));
            return;
        }
        if (System.currentTimeMillis() > Long.parseLong(content)){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服试道报名已经结束。"));
            return;
        }
        OneThreadService oneThreadService = SpringUtils.getBean(OneThreadService.class);
        oneThreadService.addFightTask(0, new Runnable() {
            @Override
            public void run() {
                try {
                    Server server = serverService.getServer();
                    List<String> arrayList = kuafuService.fetch(role.getSid());
                    String newName = role.getName() + "_" + server.getName();
                    for (String name : arrayList){
                        if (name.equals(newName)){
                            MessagePusher.pushMessage(role, new RespNotifyMiscEx("角色#R" + newName + "#n数据已经在跨服专线中，不能#R重复申请。"));
                            return;
                        }
                    }
                    Request request = Request.create("http://" + kuafu.getIp() + ":" + kuafu.getGmPort() + "/haitang/scl/my/id", Request.METHOD.GET);
                    String content = Sender.create(request).setTimeout(2000).send().getContent();
                    NutMap nutMap = Json.fromJson(NutMap.class, content);
                    Role finalRole = dao.fetch(Role.class, Cnd.where("roleId", "=", role.getRoleId()));
                    finalRole.doAfterInit();
                    finalRole.setRoleId(nutMap.getInt("roleId"));
                    finalRole.setUid(nutMap.getLong("uid"));
                    finalRole.setDistName("跨服专线");
                    finalRole.setName(finalRole.getName() + "_" + server.getName());
                    Fuling fuling = (Fuling)dao.fetch(Fuling.class, (Condition) Cnd.where("role_id", "=", Integer.valueOf(role.getRoleId())));
                    fuling.setRole_id(nutMap.getInt("roleId"));
                    kuafuService.insertFuling(fuling);

                    HunQiaoData hunQiaoData = dao.fetch(HunQiaoData.class, role.getRoleId());
                    hunQiaoData.setRoleId(nutMap.getInt("roleId"));
                    kuafuService.insertHunqiao(hunQiaoData);
                    {
                        Pos pos = finalRole.getPos();
                        pos.setMapId(mapId);
                        pos.setX(x);
                        pos.setY(y);
                        pos.setDir((byte) 5);
                        kuafuService.insert(finalRole);
                    }
                    {
                        NutMap kuafuData = new NutMap();
                        kuafuData.put("kuafuUid", finalRole.getUid());
                        kuafuData.put("sid", finalRole.getSid());
                        kuafuData.put("ip", server.getSonIp());
                        kuafuData.put("port", server.getSonPort());
                        kuafuData.put("gmport", server.getGmPort());
                        kuafuData.put("uid", role.getUid());
                        request = Request.create("http://" + kuafu.getIp() + ":" + kuafu.getGmPort() + "/haitang/scl/my/login", Request.METHOD.GET).setParams(kuafuData);
                        String string = Sender.create(request).setTimeout(2000).send().getContent();
                        logger.error("插入数据=={}=={}", string,finalRole.getName());
                        MessagePusher.pushMessage(role, new RespNotifyMiscEx("角色#R" + finalRole.getName() + "#n数据已经在跨服专线中，请退到登录页面选择对应角色进入跨服专区"));
                    }
                }catch (Exception e){
                    logger.error("拷贝数据异常==", e);
                }

            }
        });
    }


    public String pointSDJYR() {
        String content = "你找我有什么事？[" + kuafu_jingji_back.getKey() + "][" + kuafu_jingji_enter_shidao.getKey() + "][离开/离开]";
        return content;
    }

    private void back(Role role, String msg, NPC npc) {
        IoSession session = SessionUtils.getSession(role.getRoleId());
        if (session != null) {
            session.closeNow();
        }
    }

    /**
     * 发放参与奖
     * @param content
     */
    public void enterReward(String content) {
        NutMap data = Json.fromJson(NutMap.class,content);
        String name = data.getString("name");
        if (!name.endsWith(serverService.getServer().getName())){
            return;
        }
        name = name.substring(0,name.lastIndexOf("_"));
        logger.error("发放参与奖=={}=={}",name,content);
        GmCommandHandler200 gmCommandHandler200 = SpringUtils.getBean(GmCommandHandler200.class);
        Role role = SpringUtils.getRoleService().getOnlinePlayer(name);
        if (role == null){
            long uid = gmCommandHandler200.getUidByName(name);
            role = SpringUtils.getRoleService().getPlayerBy(uid);
            if (role == null){
                return;
            }
        }
        int value = data.getInt("count");
        if (data.getString("type").equals("道行盒子")){
            Mail mail = SpringUtils.getMailService().createMail("跨服试道参与奖励", "跨服试道参与奖励", 1 * TimeUtil.ONE_DAY);
            String goodname = "中级法玲珑";
            ArrayList<NutMap> maps = new ArrayList<>();
            maps.add(new NutMap().setv("data", "#I物品|"+goodname+"#r"+value+"#I").setv("type", Const.rewardWupin).setv("petName", goodname).setv("value",value));
            mail.getDatas().addAll(maps);
            mailService.sendNewMail(role, mail);
        }else if (data.getString("type").equals("道行")){
            roleService.addTotalTao11111(role,value*Const.ONE_YEAR_DAY*Const.ONE_DAY_POINT);
        }
        logger.error("跨服试道获得参与奖励=={}=={}=={}",role.getRoleId(),role.getName(),content);
    }
}